﻿
using Microsoft.CodeAnalysis.CSharp.Syntax;

namespace BJYJ_Admin.Core.Utils.ResultUtils
{
    /// <summary>
    /// 消息转换工具
    /// </summary>
    public static class ErrorConverter
    {
        public static string ConvertToString(object errors, bool succcesed)
        {
            if (succcesed)
            {
                return "操作成功！";
            }
            else
            {
                if (errors == null) return "未知错误！";

                switch (errors)
                {
                    case string str:
                        return str;
                    case IEnumerable<ValidationResult> validationResults:
                        return string.Join(", ", validationResults.SelectMany(vr => vr.ErrorMessage));
                    case IEnumerable<string> stringList:
                        return string.Join(", ", stringList);
                    case Exception ex:
                        return ex.Message;
                    default:
                        // 尝试提取常见错误属性（如 Message、Error）
                        var type = errors.GetType();
                        var messageProp = type.GetProperty("Message");
                        var errorProp = type.GetProperty("Error");
                        if (messageProp != null) return messageProp.GetValue(errors)?.ToString();
                        if (errorProp != null) return errorProp.GetValue(errors)?.ToString();
                        // 其他对象序列化为 JSON
                        return JsonConvert.SerializeObject(errors);
                }
            }
        }
    }
}
